<template>
	<div>
		<el-button type="primary" size="mini" class="mar-btm-5"
		           @click="clickAddEnumMap">新增枚举映射
		</el-button>
		<el-table :data="enumMapList" border stripe class="width-100">
			<el-table-column prop="sourceEnum" label="数据类型"></el-table-column>
			<el-table-column prop="sourceEnum" label="原始枚举"></el-table-column>
			<el-table-column prop="targetEnum" label="目标枚举"></el-table-column>
			<el-table-column label="操作" width="150px">
				<template #default="scope">
					<a class="font-weight-bold font-color-primary cursor-pointer"
					   @click="clickEditEnumMap(scope.$index)">编辑</a>
					<a class="font-weight-bold font-color-primary cursor-pointer mar-lft"
					   @click="clickCopyEnumMap(scope.$index)">复制</a>
					<a class="table-opt-btn font-color-danger font-weight-bold cursor-pointer mar-lft"
					   @click="clickDeleteEnumMap(scope.$index)">删除</a>
				</template>
			</el-table-column>
		</el-table>

		<el-dialog
			:title="`${!isEditEnumMap ? '新增' : '编辑'}参数枚举映射`"
			:visible.sync="showEnumMapDialog"
      :close-on-click-modal="false"
			width="550px">
			<el-form
				:ref="enumMapFormRef"
				:model="enumMapForm"
				:rules="enumMapFormRules"
				size="small"
				label-width="85px">
				<el-form-item label="数据类型" prop="enumDataType">
					<el-radio-group
						v-model="enumMapForm.enumDataType"
						@change="enumMapForm.sourceEnum = ''">
						<el-radio
							v-for="(dataType, idx) in commonConfig.dataType" :key="idx"
							:label="dataType.value">{{dataType.label}}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="原始枚举" prop="sourceEnum">
					<el-input
						v-if="['string', 'hex'].includes(enumMapForm.enumDataType)"
						v-model="enumMapForm.sourceEnum" placeholder="请输入原始枚举值" class="width-100"/>
					<el-input-number
						v-else-if="['long', 'decimal'].includes(enumMapForm.enumDataType)"
						v-model="enumMapForm.sourceEnum" placeholder="请填写原始枚举值" class="width-100"/>
					<el-select
						v-else-if="['boolean'].includes(enumMapForm.enumDataType)"
						v-model="enumMapForm.sourceEnum" class="width-100">
						<el-option label="true" :value="true"></el-option>
						<el-option label="false" :value="false"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="关联类型" prop="relationType">
					<el-select v-model="enumMapForm.relationType" placeholder="请选择关联控制类型" class="width-100">
						<el-option
							v-for="relationType in enumRelationTypeData" :key="relationType.value"
							:label="relationType.label" :value="relationType.value"></el-option>
					</el-select>
				</el-form-item>
				<div v-if="enumMapForm.relationType === 'device'">
					<el-form-item label="设备类别" prop="targetDeviceType">
						<el-select
							v-model="enumMapForm.targetDeviceType"
							filterable placeholder="请选择目标设备类别" class="width-100">
							<el-option
								v-for="deviceType in deviceTypeData" :key="deviceType._id"
								:label="deviceType.label" :value="deviceType._id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="通用方法" prop="generalCommand">
						<el-select v-model="enumMapForm.generalCommand" clearable filterable
						           class="width-100" placeholder="请选择通用命令">
							<el-option-group v-for="(group, idx) in genCommandGroupData" :key="idx" :label="group.label">
								<el-option v-for="(opt, idx) in group.options" :key="idx"
								           :label="`${opt.methodName} ${opt.methodAlias || ''}`" :value="opt._id">
									<span>{{opt.methodName}}</span>
									<span class="mar-lft font-color-warning">{{opt.methodAlias || ''}}</span>
								</el-option>
							</el-option-group>
						</el-select>
					</el-form-item>
					<el-form-item label="目标属性" prop="targetProp">
						<el-select
							v-model="enumMapForm.targetProp"
							placeholder="请选择目标属性名称"
							class="width-100">
							<el-option
								v-for="param in ctrlParamOptions" :key="param.paramKey"
								:label="`${param.paramKey} ${param.paramAlias}`" :value="param.paramKey">
								<span>{{param.paramKey}}</span>
								<span class="mar-lft-10 font-color-warning">{{param.paramAlias}}</span>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="目标枚举" prop="targetEnum">
						<el-select
							v-model="enumMapForm.targetEnum" filterable
							placeholder="请选择目标枚举值" class="width-100">
							<el-option
								v-for="paramEnum in paramEnumOptions" :key="paramEnum.paramKey"
								:label="`${paramEnum.key} ${paramEnum.alias}`" :value="paramEnum.key">
								<span>{{paramEnum.key}}</span>
								<span class="mar-lft-10 font-color-warning">{{paramEnum.alias}}</span>
							</el-option>
						</el-select>
					</el-form-item>
				</div>
				<div v-if="enumMapForm.relationType === 'scene'">
					<el-form-item label="情景别名" prop="sceneName">
						<el-input v-model="enumMapForm.sceneName" placeholder="请填写情景别名"></el-input>
					</el-form-item>
				</div>
				<el-form-item label="备注" prop="remarks">
					<el-input type="textarea" v-model="enumMapForm.remarks" placeholder="请填写备注"></el-input>
				</el-form-item>
				<div class="text-align-right">
					<el-form-item>
						<el-button size="medium" @click="showEnumMapDialog = false">取消</el-button>
						<el-button size="medium" type="primary" @click="enumMapFormSubmit">提交</el-button>
					</el-form-item>
				</div>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
	import GenCommParams from "@/page/relationData/generalCommand/partial/GenCommParams.vue";
	import {commonConfig} from "@/config/common";
	import {confirmHandle, deepCopy} from "@/utils";
	import {commonString} from "@/config/string";

	export default {
		name: "ParamEnumMapList",
		components: {GenCommParams},
		props: {
			deviceTypeData: {
				type: Array,
			  default: () => {
					return [];
			  }
		  },
		  enumMapList: {
				type: Array,
			  default: () => {
					return [];
			  }
		  },
			sourceDeviceType: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				commonConfig: commonConfig,
				enumRelationTypeData: [
					{
						label: '关联设备控制',
						value: 'device'
					},
					{
						label: '关联情景控制',
						value: 'scene'
					}
				],
				showEnumMapDialog: false,
				isEditEnumMap: false,
				curEnumMapIdx: 0,
				enumMapFormRef: 'enumMapFormRef',
				enumMapForm: {
					enumDataType: commonConfig.dataType[0].value,
					sourceEnum: '',
					relationType: 'device',
					targetDeviceType: '',
					generalCommand: '',
					targetProp: '',
					targetPropInArray: '',
					targetEnum: "",
					enumAlias: "",
					sceneName: '',
					remarks: ''
				},
				enumMapFormRules: {
					enumDataType: [{required: true, message: '请选择枚举数据类型', trigger: 'change'}],
					sourceEnum: [{required: true, message: '请输入原始枚举值', trigger: 'change'}],
					relationType: [{required: true, message: '请选择关联控制类型', trigger: 'change'}],
					targetDeviceType: [{required: true, message: '请选择目标设备类型', trigger: 'change'}],
					generalCommand: [{required: true, message: '请选择通用命令', trigger: 'change'}],
					targetProp: [{required: true, message: '请选择目标属性', trigger: 'change'}],
					targetEnum: [{required: true, message: '请输入目标枚举值', trigger: 'blur'}],
					sceneName: [{required: true, message: '请输入目标情景别名', trigger: 'blur'}],
				},
				genCommandSrcData: [],
				genCommandGroupData: [],
			};
		},
		computed: {
			methodTypeText() {
				return (type) => {
					const methodType = commonConfig.commandType.find(t => t.value === type) || {};
					return methodType.label || commonString.dash;
				}
			},
			methodNameText() {
				return (methodId) => {
					const methodType = this.genCommandSrcData.find(gc => gc._id === methodId) || {};
					return methodType.methodName || commonString.dash;
				}
			},
			paramMapTypeText() {
				return (type) => {
					const mapWay = commonConfig.commandMapWay.find(w => w.value === type) || {};
					return mapWay.label || commonString.dash;
				}
			},
			ctrlParamOptions() {
				const genCommand = this.genCommandSrcData.find(gc => {
					return gc._id === this.enumMapForm.generalCommand;
				}) || {};
				const {controlParams = []} = genCommand;
				return controlParams;
			},
			paramOptionsInArray() {
				const paramOptions = [];
				this.ctrlParamOptions.forEach(param => {
					const {paramKey = ''} = param;
					!paramKey.includes('List') && paramOptions.push(param);
				});
				return paramOptions;
			},
			paramEnumOptions() {
				const selectParam = this.ctrlParamOptions.find(p => {
					return p.paramKey === this.enumMapForm.targetProp;
				}) || {};
				return selectParam.enumList || [];
			}
		},
		watch: {
			'enumMapForm.targetDeviceType': {
				handler() {
					this.getGenCommandData();
				},
				immediate: true
			}
		},
		created() {
			this.initEnumMapForm();
		},
		methods: {
			initEnumMapForm() {
				this.enumMapForm = {
					enumDataType: commonConfig.dataType[0].value,
					sourceEnum: '',
					relationType: 'device',
					targetDeviceType: '',
					generalCommand: '',
					targetProp: '',
					targetPropInArray: '',
					targetEnum: "",
					sceneName: ''
				}
			},
			resetEnumMapForm() {
				this.initEnumMapForm();
				const enumMapForm = this.$refs[this.enumMapFormRef];
				enumMapForm && enumMapForm.resetFields();
			},
			getGenCommandData() {
				if (!this.enumMapForm.targetDeviceType) return;
				const deviceType = this.deviceTypeData.find(dt => {
					return dt._id === this.enumMapForm.targetDeviceType;
				}) || {};
				const param = {deviceType: deviceType._id};
				API.genCommand.genCommAll(param).then(result => {
					const {data = []} = result;
					this.genCommandSrcData = data;
					this.genCommandGroupData = [];
					// 将通用命令根据命令类型分组
					const initGenCommData = commonConfig.commandType.map(ct => {
						return {...ct, options: []};
					});
					data.forEach(d => {
						const genComm = initGenCommData.find(f => {
							return f.value === d.generalCommandType;
						});
						genComm && (genComm.options.push(d));
					});
					initGenCommData.forEach(gc => {
						const {options = []} = gc;
						options.length && (this.genCommandGroupData.push(gc));
					});
				}).catch(err => {
				});
			},
			clickAddEnumMap() {
				// this.$refs[this.mapRuleFormRef].validate(valid => {
				// 	if (!valid) return;
					this.isEditEnumMap && this.resetEnumMapForm();
					this.enumMapForm.targetDeviceType = this.sourceDeviceType;
					this.showEnumMapDialog = true;
					this.isEditEnumMap = false;
				// });
			},
			clickEditEnumMap(idx) {
				const enumMap = deepCopy(this.enumMapList[idx]);
				this.showEnumMapDialog = true;
				this.isEditEnumMap = true;
				this.enumMapForm = enumMap;
				this.curEnumMapIdx = idx;
			},
			clickCopyEnumMap(idx) {
				const enumMap = deepCopy(this.enumMapList[idx]);
				this.showEnumMapDialog = true;
				this.isEditEnumMap = false;
				this.enumMapForm = enumMap;
			},
			clickDeleteEnumMap(idx) {
				confirmHandle({label: `确定要删除参数枚举映射吗?`}).then(() => {
					this.enumMapList.splice(idx, 1);
				}).catch(() => {
				});
			},
			enumMapFormSubmit() {
				const enumMapForm = deepCopy(this.enumMapForm);
				if (!this.isEditEnumMap) {
					this.enumMapList.push(enumMapForm);
				} else {
					this.enumMapList.splice(this.curEnumMapIdx, 1, enumMapForm);
				}
				this.showEnumMapDialog = false;
			},
		},
	}
</script>

<style scoped lang="less">

</style>
